var relationData;

var MethodData;

//sendData is the deliver json data
var sendData={};
var deleteData={};

function addEditDiv(){
	$("#treeEdit").append("<h3>view tree and edit node</h3><br>"			
			+"<label for='xPath'> path:</label> "
			+"<input type='text' id='xPath' >"
			+"<label for='value'> value:</label> "
			+"<input type='text' id='value' ><br>"
			+"<label for='dataElement'> dataElement:</label> "
			+"<div id='dataElement'></div><br>"
			+"<input type='button' class='btn btn-default' id='add' value='add'>"
			+"<input type='button' class='btn btn-default' id='delete' value='delete'>"
			+"<input type='button' class='btn btn-default' id='deleteNode' value='delete this node'>"
			+"<input type='button' class='btn btn-default' id='cancel' value='cancel'>");
}

//从relation数据中获取"csv-key"项，并生成description的button
function addColumn(data)
{ 
	dataSource=data;
    var keys=data["csv-key"].split('|');
    $.each(keys,function(k,v){
    	$("#dataElement").append("<button type='button' class='btn btn-default data' >"+v+"</button>");
    	
    }); 
 }

function getRelationData()
{
    $.ajax({
	url:"../rest/relation/getRelationContent",
	data :{"path":$("#path").val()},
	dataType : "JSON",
	method:"POST",
	success:function(data){	 
		debugger
	    relationData=data;	  
		
	    getMethofdData(data.operationName);
	},
	error:function(data){
	   // console.log();
	}
    });
 }


function getMethofdData(operation)
{
	debugger;
    $.ajax({
	  type: "POST",
	  url: "../rest/XMLNode",
	  data: {"OperationName":operation},
	  dataType: "JSON",
	  success:function(data){
		  debugger
	      LoadingTree(data);
		  editTreeNode(); 
	  }
	});

}


function LoadingTree(data)
{
	debugger
    $('#treeDiv').jstree({ 'core' : {
    'data' :data,
       }}
    ).bind("select_node.jstree", function (event, data) { 
    	var xpath=data.node.original.path;
    	var value=data.node.original.value;
    	   debugger
    	   $("#treeEdit").html("");
    	   addEditDiv();
    	   $("#xPath").attr("value",xpath);
    	   $("#value").attr("value",value);
    	   addColumn(relationData);
    	   editButton();
    	   addJson();
   		   deleteJson();
       })
//    $("#treeDiv").jstree("open_all");
}

function editTreeNode(){
	$("#treeDiv a").click(function(){
		debugger
		$("#treeEdit").show();
	})
}

function editButton(){
	$("#dataElement button").click(function(){
		$("#value").attr("value",$(this).text());
	})
}

function addJson(){
	$("#add").click(function(){
		debugger
		if($("#xPath").val()!=""&&$("#value").val()!="")
			sendData[$("#xPath").val()]=$("#value").val();
	})
}

function deleteJson(){
	$("#delete").click(function(){
		if($("#xPath").val()!=""&&$("#value").val()!="")
			delete sendData[$("#xPath").val()];
	})
	
}

$(function(){
	getRelationData(); 
	
});